package org.example;



import freemarker.template.Template;
import org.example.base.TemplateBase;
import org.example.base.impl.*;
import org.example.config.FreeMarkerTemplateConfig;
import org.example.entity.BasicInfoEntity;
import org.example.entity.TableEntity;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 * 生成代码
 */
public class CodeGenerate {

    /**
     * 根据模板生成
     *
     * @param base 模板接口
     * @throws Exception
     */
    private void generateFileByTemplate(TemplateBase base) throws Exception {
        Writer out = null;
        try {
            Template template = FreeMarkerTemplateConfig.getTemplate(base.getTemplateName());
            FileOutputStream fos = new FileOutputStream(base.getFile());
            out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
            template.process(base.getDataMap(), out);
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            //清空缓存
            FreeMarkerTemplateConfig.clearCache();
            if (out != null)
                out.close();
        }

    }

    /**
     * 创建文件
     *
     * @param basicInfoEntity 基本信息
     * @param tableInfo       表信息
     * @throws Exception
     */
    public void createFile(BasicInfoEntity basicInfoEntity, TableEntity tableInfo) throws Exception {

        if (basicInfoEntity.getEntity() != null) {
            TemplateEntity templateEntity = new TemplateEntity(basicInfoEntity, tableInfo);
            generateFileByTemplate(templateEntity);
        }
        if (basicInfoEntity.getDao() != null) {
            TemplateDAO templateDAO = new TemplateDAO(basicInfoEntity, tableInfo);
            generateFileByTemplate(templateDAO);
        }
        if (basicInfoEntity.getXml() != null) {
            TemplateXml templateXml = new TemplateXml(basicInfoEntity, tableInfo);
            generateFileByTemplate(templateXml);
        }
        if (basicInfoEntity.getService() != null) {
            TemplateService templateService = new TemplateService(basicInfoEntity, tableInfo);
            generateFileByTemplate(templateService);
        }
        if (basicInfoEntity.getServiceImpl() != null) {
            TemplateServiceImpl templateServiceImpl = new TemplateServiceImpl(basicInfoEntity, tableInfo);
            generateFileByTemplate(templateServiceImpl);
        }
        if (basicInfoEntity.getController() != null) {
            TemplateController templateController = new TemplateController(basicInfoEntity, tableInfo);
            generateFileByTemplate(templateController);
        }
    }
}
